package org.fatmansoft.teach.controllers;

import org.fatmansoft.teach.models.Assessment;
import org.fatmansoft.teach.models.Course;
import org.fatmansoft.teach.models.Student;
import org.fatmansoft.teach.payload.request.DataRequest;
import org.fatmansoft.teach.payload.response.DataResponse;
import org.fatmansoft.teach.repository.AssessmentRepository;
import org.fatmansoft.teach.repository.CourseRepository;
import org.fatmansoft.teach.repository.PersonRepository;
import org.fatmansoft.teach.repository.StudentRepository;
import org.fatmansoft.teach.util.CommonMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/assessment")
public class AssessmentController {

    @Autowired
    private AssessmentRepository assessmentRepository;
    @Autowired
    private StudentRepository studentRepository;

    private boolean sendMission = false;
    //查
    //怎么查出来呢？可以通过被评价者的名字学号或者评价者的名字学号查出来
    //这里先写被评价者的吧

    //10.29   如果没有数据，就默认查找所有的学生
    //如果有数据，就查出对应学生
    public List getAssessmentMapList(String numName) {
        if(numName == null)
            numName = "";
        List<Assessment> aList = assessmentRepository.findAssessmentListByNumName(numName);  //数据库查询操作
        List dataList = new ArrayList();
        Map m;
        for (Assessment a : aList) {
            m = new HashMap();
            m.put("assessmentId", a.getAssessmentId()+"");
            m.put("num",a.getStudent().getPerson().getNum());
            m.put("name",a.getStudent().getPerson().getName());
            m.put("num2",a.getStudentEvaluator().getPerson().getNum());
            m.put("name2",a.getStudentEvaluator().getPerson().getName());
            m.put("morality",a.getMorality()+"");
            m.put("talent",a.getTalent()+"");
            m.put("whole",a.getWhole()+"");
            m.put("assessment",a.getAssessment());
            dataList.add(m);
        }
        return dataList;
    }



    //初始化方法，查出来所有的信息
    //管理员端初始化
    @PostMapping("/assessmentInit")
    //@PreAuthorize("hasRole('ADMIN')")
    public DataResponse assessmentInit(@Valid @RequestBody DataRequest dataRequest) {
        /*System.err.println(studentId.get("data"));
        System.err.println(studentId.get("data").get("studentId"));*/
//        System.err.println("qqq");
        List dataList = getAssessmentMapList("");
        return CommonMethod.getReturnData(dataList);  //按照测试框架规范会送Map的list
    }


    //查找方法
    //根据被评价者的姓名学号进行查找
    @PostMapping("/assessmentQuery")
    @PreAuthorize("hasRole('ADMIN')")
    public DataResponse assessmentQuery(@Valid @RequestBody DataRequest dataRequest) {
        String numName = dataRequest.getString("numName");
        List dataList = getAssessmentMapList(numName);
        return CommonMethod.getReturnData(dataList);  //按照测试框架规范会送Map的list
    }



    //删
    //把当前选中的记录删除
    @PostMapping("/assessmentDelete")
    public DataResponse assessmentDelete(@Valid @RequestBody DataRequest dataRequest) {
        Integer asId = dataRequest.getInteger("assessmentId");
        Assessment as = null;
        Optional<Assessment> op;
        if (asId!=null){
            op = assessmentRepository.findById(asId);
            if (op.isPresent()){
                as = op.get();
            }
        }
        if (as!=null){
            assessmentRepository.delete(as);
        }
        return CommonMethod.getReturnMessageOK();
    }

    //管理员端发布任务
    @PostMapping("/assessmentMission")
    public DataResponse assessmentMission(@Valid @RequestBody DataRequest dataRequest) {
        //清空所有的记录
        assessmentCancel(dataRequest);
        //开始发布任务
        //找出所有的学生
        //二重循环在数据库中建立记录
        List<Student> studentList = studentRepository.findAll();
        if(studentList==null||studentList.size()==0)
            return CommonMethod.getReturnMessageError("无学生");
        if(studentList.size()==1)
            return CommonMethod.getReturnMessageError("只有1个学生，不可互评");
        int studentNumber = studentList.size();
        //这个评者数目如何设置？？应该就是studentnum-1
        //int evaluatorNumber = studentNumber >= 6 ? 5 : studentNumber - 1;
        int evaluatorNumber = studentNumber - 1;

        //在分配的过程中，每次取出来一个学生，然后，给他设置所有他要评价的/评价他的人
        //先依次取出来所有的学生，然后添加evaluatorNumber条记录  就是在数据库中把所有的n*(n-1)条记录先加上
        //这个时候是建立的被评价者的信息
        for (int i = 0; i < studentNumber; i++) {
            Student student = studentList.get(i);
            //给每个学生增加被评价记录
            for (int j = 0; j < evaluatorNumber; j++) {
                Assessment assessment = new Assessment();
                //难道不是自增的吗？
                // assessment.setId(getNewAssessmentId());
                assessment.setStudent(student);
                //assessment.setNumber(j + 1);
                //System.err.println(assessment.getId() + " " + assessment.getStudentBeingEvaluated().getStudentName());
                assessmentRepository.save(assessment);
            }
        }

        //给每一个被评价者分配评价者
        //两层for循环
        //每次取出一个学生，然后第二层是除了他之外的所有学生,
        //首先查出这个学生的所有的被评价记录，然后评价者被是这些剩下的学生
        for (int i = 0; i < studentNumber; i++) {
            Student student = studentList.get(i);
            //这是这个学生的待添加评价者的记录
            //问题出在这里，没查出来？？
            List<Assessment> studentAssessArray = assessmentRepository.findAssessmentListByNumName(student.getPerson().getNum());
            List<Student> studentEvaluatorList = studentRepository.findAll();
            studentEvaluatorList.remove(student);

            //给每个学生增加评价者
            //现在还有一个问题
            //我似乎应该建立另外一个叫评价者的list，然后把被评价者删除，这样j和studentEvaluator就匹配起来了
            for (int j = 0; j < evaluatorNumber; j++) {
                Student studentEvaluator = studentEvaluatorList.get(j);
                //学生和评价者不同时，分配
                //不过似乎已经不同了
                if (student.getStudentId()!=studentEvaluator.getStudentId()){
                    Assessment assessment = studentAssessArray.get(j);
                    assessment.setStudentEvaluator(studentEvaluator);
                    assessmentRepository.save(assessment);
                }
                //难道不是自增的吗？
                // assessment.setId(getNewAssessmentId());
                //assessment.setStudent(student);
                //assessment.setNumber(j + 1);
                //System.err.println(assessment.getId() + " " + assessment.getStudentBeingEvaluated().getStudentName());
            }
        }
        //先这么写
        //这里不用返回一个数组之类的吗？
        //那他怎么实现数据的传输呢？
        //前端调用的这个方法，怎么得到数据库的数据呢？

        List dataList = getAssessmentMapList("");
        return CommonMethod.getReturnData(dataList);

        //其实也可以不返回list
        //然后在前端调用查询方法
    }
    //结束任务
    //目前这里的思路是删除所有记录
    @PostMapping("/assessmentCancel")
   // @PreAuthorize(" hasRole('ADMIN')")
    public DataResponse assessmentCancel(@Valid @RequestBody DataRequest dataRequest) {
        List<Assessment> assessmentList = assessmentRepository.findAll();
        for (int i = 0; i < assessmentList.size(); i++) {
            Assessment as = assessmentList.get(i);
            assessmentRepository.delete(as);
        }
        //sendMission = false;
        return CommonMethod.getReturnData(getAssessmentMapList(""));
    }



    //初始化方法，查出来所有的信息
    //学生端初始化
    @PostMapping("/studentAssessmentInit")
    //@PreAuthorize("hasRole('ADMIN')")
    public DataResponse studentAssessmentInit(@Valid @RequestBody DataRequest dataRequest) {
        //根据他自己的name查，初始化显示他的待评价
        String username = CommonMethod.getUsername();
        List<Assessment> aList = assessmentRepository.findAssessmentListByEvaluatorNumName(username);  //数据库查询操作
        List dataList = new ArrayList();
        Map m;
        for (Assessment a : aList) {
            m = new HashMap();
            m.put("assessmentId", a.getAssessmentId()+"");
            m.put("num",a.getStudent().getPerson().getNum());
            m.put("name",a.getStudent().getPerson().getName());
            m.put("num2",a.getStudentEvaluator().getPerson().getNum());
            m.put("name2",a.getStudentEvaluator().getPerson().getName());
            m.put("morality",a.getMorality()+"");
            m.put("talent",a.getTalent()+"");
            m.put("whole",a.getWhole()+"");
            m.put("assessment",a.getAssessment());
            dataList.add(m);
        }
        return CommonMethod.getReturnData(dataList);  //按照测试框架规范会送Map的list
    }



    //学生端保存对别人的评价
    //保存一条记录
    //主体功能应该是教师端发布互评任务，一旦发布，就会自动生成这些记录，只不过暂时没有数据
    //所以等到学生评价时，就已经存在了
    //因为他save就是单纯的save,因为前期都已经建好了记录，只要根据id查出来进行更改保存即可
    //学生端进行更改的时候，需要用到这个save方法
    @PostMapping("/studentAssessmentSave")
    public DataResponse studentAssessmentSave(@Valid @RequestBody DataRequest dataRequest) {
        Integer assessmentId = dataRequest.getInteger("assessmentId");
        String assessment = dataRequest.getString("assessment");
        Integer morality = dataRequest.getInteger("morality");
        Integer talent = dataRequest.getInteger("talent");
        Integer whole = dataRequest.getInteger("whole");

        Optional<Assessment> op;
        Assessment a= null;

        if(assessmentId != null) {
            op = assessmentRepository.findById(assessmentId);
            if(op.isPresent())
                a= op.get();
        }

        if (a!=null){
            a.setMorality(morality);
            a.setTalent(talent);
            a.setWhole(whole);
            a.setAssessment(assessment);
            assessmentRepository.save(a);
        }
        return CommonMethod.getReturnMessageOK();
    }

    //学生端查看别人对自己的评价
    @PostMapping("/getMyAssessment")
    //@PreAuthorize("hasRole('ADMIN')")
    public DataResponse getMyAssessment(@Valid @RequestBody DataRequest dataRequest) {
        //需要获取出当前登录用户的信息，不过这个过程由前端完成，然后传递给后端就可以了
        String username = CommonMethod.getUsername();
        List dataList = getAssessmentMapList(username);
        return CommonMethod.getReturnData(dataList);
    }

    //学生端查找
    @PostMapping("/stuAssessmentQuery")
    //@PreAuthorize("hasRole('ADMIN')")
    public DataResponse stuAssessmentQuery(@Valid @RequestBody DataRequest dataRequest) {
        //需要获取出当前登录用户的信息，不过这个过程由前端完成，然后传递给后端就可以了
        String username = CommonMethod.getUsername();
        String numName = dataRequest.getString("numName");
        List<Assessment> aList = assessmentRepository.findStuAssessmentListByNumName(numName,username);  //数据库查询操作
        List dataList = new ArrayList();
        Map m;
        for (Assessment a : aList) {
            m = new HashMap();
            m.put("assessmentId", a.getAssessmentId()+"");
            m.put("num",a.getStudent().getPerson().getNum());
            m.put("name",a.getStudent().getPerson().getName());
            m.put("num2",a.getStudentEvaluator().getPerson().getNum());
            m.put("name2",a.getStudentEvaluator().getPerson().getName());
            m.put("morality",a.getMorality()+"");
            m.put("talent",a.getTalent()+"");
            m.put("whole",a.getWhole()+"");
            m.put("assessment",a.getAssessment());
            dataList.add(m);
        }
        return CommonMethod.getReturnData(dataList);
    }

}




